package com.zucc.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求拦截器
 */
@Component
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {


    /**
     * 请求处理前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        request.setAttribute("startTime", System.currentTimeMillis());
        // 获取账号类型
        String type = request.getHeader("type");
//        // 获取账号
//        String account = request.getHeader("account");
//        // 获取令牌
//        String token = request.getHeader("token");
//        if (StringUtils.isBlank(account) || StringUtils.isBlank(account) || StringUtils.isBlank(account)) {
//            response.getWriter().write(new ObjectMapper().writeValueAsString(new Result(ResultCodeEnum.ERROR, "账号无权访问")));
//            return false;
//        }
        // 判断接口角色权限
//        if (handler instanceof HandlerMethod) {
//            RoleCheck roleCheck = ((HandlerMethod) handler).getMethod().getAnnotation(RoleCheck.class);
//            // 所有角色都可以访问
//            if (Objects.isNull(roleCheck) ) {
//                return true;
//            }
//            // 没有指定的角色权限
//            if (!Arrays.asList(roleCheck.roles()).contains(type)) {
//                throw new RuntimeException("账号无权访问");
//            }
//        }
//        // 调试
//        if (type.equals("admin")) {
//            return true;
//        }
//        // 拼接redis缓存userKey
//        String userKey = new StringBuilder(type).append(":").append(account).toString();
//        // 获取缓存令牌
//        Object tokenCache = redisUtil.hget(userKey, "token");
//        // 没有登陆或者token错误
//        if (tokenCache == null || !tokenCache.equals(token)) {
//            // 返回错误信息
////            response.setHeader("Content-Type", "application/json;charset=UTF-8");
//            response.getWriter().write(new ObjectMapper().writeValueAsString(new Result(ResultCodeEnum.ERROR, "账号在其他地方登陆")));
//            return false;
//        }
        return true;
    }

    /**
     * 请求处理结果即将返回前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        request.setAttribute("endTime", System.currentTimeMillis());
    }

    /**
     * 请求处理完成后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (request.getAttribute("endTime") != null) {
            if (request.getRequestURI().contains("/devices")) {
                request.removeAttribute("startTime");
                request.removeAttribute("endTime");
                return;
            }
            log.info("uri {} method {} time {} ms", request.getRequestURI(), request.getMethod(), (long) request.getAttribute("endTime") - (long) request.getAttribute("startTime"));
        }
        request.removeAttribute("startTime");
        request.removeAttribute("endTime");
    }
}
